const express = require("express")
const md5 = require("md5")
const adminModel = require("../db/model/adminModel")
const jwt = require("../utils/jwt")
const router = express.Router()
router.post("/login", async (req, res) => {
  const { username, password } = req.body
  const admin = await adminModel.findOne(
    { username, password: md5(password) },
    { password: 0 }
  )
  if (admin) {
    const token = jwt.encode(admin._id)
    await adminModel.updateOne({ id: admin._id }, { $set: { token } })
    res.send({ success: true, msg: "登录成功", token, admin })
  } else {
    res.send({ success: false, msg: "登录失败，请输入正确的用户名和密码" })
  }
})

router.post("/verifyAdmin", async (req, res) => {
  const { authorization } = req.body
  if (authorization) {
    const admin = await adminModel.findOne(
      { token: authorization },
      { password: 0 }
    )
    if (admin) {
      const result = jwt.decode(authorization)
      if (result.expires > Date.now()) {
        res.send({ success: true, msg: "token有效" })
        return
      }
    }
  }
  res.send({ success: false, msg: "token无效" })
})

router.post("/logout", async (req, res) => {
  const { id } = req.body
  await adminModel.updateOne({ _id: id }, { $set: { token: "" } })
  res.send({ success: true, msg: "退出成功" })
})

module.exports = router
